
//控制设置菜单显示隐藏
$('#toggle_set_menu').click(function(){
    $('.cog_menu').toggle();
});

//显隐群员列表
$('.top_bar .show_list').click(function(){
    var obj_list = $('.top_bar .obj_list');
    var obj_name = $('.top_bar .obj_name');
    if(obj_list.hasClass('hide')){
        var index = layer.load(1);
        Im.conn.queryRoomMember({
            roomId: obj_name.attr('tag'),
            success: function (members) {
                layer.close(index);
                var username, face, line = {}, html = '';
                var user_list = Im.session('friend_list');
                for (var o in members) {
                    username = members[o].jid.split('_');
                    username = username[1].split('@');
                    for(var i = 0; i < user_list.length; i++){
                        if(user_list[i].username == username[0]){
                            line = user_list[i];
                            break;
                        }
                    }
                    if(line.username){
                        face = line.face ? line.face : USER_DEF_HEAD;
                        if(obj_name.attr('owner') == Im.data.username){
                            html += '<li><div class="user_info"><img src="'+face+'">'+line.nickname+'</div>' +
                                '<div class="option"><span class="fa fa-close clear_group_user" ' +
                                'onclick="clear_user(this, \''+line.username+'\')"></span></div></li>';
                        }else{
                            html += '<li><div class="user_info"><img src="'+face+'">'+line.nickname+'</div></li>';
                        }
                        line = {};
                    }
                }
                obj_list.empty();
                obj_list.append(html);
                obj_list.removeClass('hide');
            }
        });
    }else{
        obj_list.addClass('hide');
    }
});

$('.top_bar .fa-cog').click(function(){
    $('.top_conf_menu').toggle();
});

//设置菜单触发事件绑定
$('.cog_menu li').click(function(){
    switch ($(this).attr('action')){
        case 'modify_name':
            layer.prompt({title:'请输入新的用户名.', value:$(this).attr('def')}, function(msg){
                var index = layer.load(1);
                $.post(UPDATE_INFO_URL, {nickname:msg}, function(res){
                    layer.close(index);
                    if(res.code == 1){
                        location.reload();
                    }else{
                        layer.msg(res.msg);
                    }
                }, 'JSON');
            });
            break;
        case 'add_group':
            layer.open({
                type: 2,
                title: '创建群组',
                shadeClose: true,
                shade: 0.8,
                area: ['80%', '80%'],
                content: ADD_GROUP_URL //iframe的url
            });
            break;
        case 'add_room':
            layer.open({
                type: 2,
                title: '创建聊天室',
                shadeClose: true,
                shade: 0.8,
                area: ['80%', '80%'],
                content: ADD_ROOM_URL //iframe的url
            });
            break;
        case 'exit':
            layer.confirm('确定要退出吗?', {icon:3}, function(){
                var index = layer.load(1);
                $.post(EXIT_URL, {}, function(res){
                    layer.close(index);
                    if(res.status == 1){
                        Im.conn.close();
                        location.assign(LOGIN_URL);
                        delete sessionStorage['is_send_online'];        //移除上线提示标记
                    }else{
                        layer.msg(res.msg);
                    }
                }, 'JSON');
            });
            break;
    }
});

/**
 * 联系人切换事件绑定
 */
$('.left_bar .chat_items li ').click(function(){
    var action = $(this).attr('class');
    Im.displayChatList(action);
    Im.session('talk_type', action);       //设置当前聊天类型session
    $('.top_bar .top_conf_menu').hide();        //隐藏聊天界面设置菜单
    $('.top_bar .top_conf .fa-cog').hide();        //隐藏聊天界面设置按钮
    $('.chat_panel .chat_shade').removeClass('hide');       //显示遮罩层
    $('.left_bar .chat_items li span').removeClass('action');
    $(this).find('span').addClass('action');

    $('#search_bar').val('');
    $('.chat_list .chat_list_item ').each(function(){
        if(!$(this).hasClass('hide')){
            $(this).find('.chat_obj').show();
        }
    });

});

/**
 * 格式化时间戳
 * @returns {string}
 */
function formatTime() {
    var date = new Date();
    var days = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
    var hour = [date.getHours(), date.getMinutes(), date.getSeconds()];
    return days.join('-') + ' ' + hour.join(':');
}

/**
 * 删除群成员
 * @param dom
 * @param user
 */
function clear_user(dom, user){
    var roomId = $('.top_bar .obj_name').attr('tag');
    var option = {
        affiliation: 'owner',                       // 写死
        roomId: roomId,                    // 群组ID
        success: function () {
            $(dom).parents('li').remove();
            layer.msg('删除成功.');
        },
        to: user                               // 需要删除的成员ID
    };
    Im.conn.addToGroupBlackList(option);
}

/**
 * 修改群组信息
 */
function modify_group(){
    layer.open({
        type: 2,
        title: '修改群组信息',
        shadeClose: true,
        shade: 0.8,
        area: ['80%', '80%'],
        content: MOD_GROUP_URL //iframe的url
    });
}

/**
 * 删除群组
 */
function close_group(){
    layer.confirm('您确定要解散群组吗?', function(){
        var obj_name = $('.top_bar .obj_name');
        var option = {
            reason: 'delete group',
            roomId: obj_name.attr('tag'),
            success: function () {
                location.reload();
            }
        };
        Im.conn.destroyGroup(option);
    });
}

/**
 * 退出群组
 */
function exit_group(){
    var obj_name = $('.top_bar .obj_name');
    var option = {
        to: Im.data.username,
        roomId: obj_name.attr('tag'),
        success: function () {
            location.reload();
        },
        error: function () {
            layer.msg('退出群组失败.');
        }
    };
    Im.conn.leaveGroupBySelf(option);
}

/**
 * 解散聊天室
 */
function close_room(){
    var obj_name = $('.top_bar .obj_name');
    var index = layer.load();
    var data = {username:Im.data.username, roomid:obj_name.attr('room_id')};
    Im.request('room/deleteRoom', data, function(res){
        layer.close(index);
        if(res.code == 1){
            location.reload();
        }else{
            layer.msg(res.msg);
        }
    });
}

/**
 * 退出聊天室
 */
function exit_room(){
    var obj_name = $('.top_bar .obj_name');
    Im.conn.quitChatRoom({
        roomId:  obj_name.attr('tag') // 聊天室id
    });
}

/**
 * 图片显示层
 * @param dom
 */
function viewImage(dom){
    var viewer = document.createElement('div');
    viewer.setAttribute('id', 'image_view_floor');
    var img = document.createElement('img');
    var p = document.createElement('p');
    img.setAttribute('src', dom.src);
    viewer.appendChild(p);
    viewer.appendChild(img);
    $('body').append(viewer);
    document.getElementById('image_view_floor').onclick = function(){
        $(this).remove();
    }
}
/**
 * 编码字符
 * @param str
 * @returns {XML|string|*}
 */
function html_encode(str){
    str = str.replace(/\</g, '&lt;');
    str = str.replace(/\>/g, '&gt;');
    str = str.replace(/\'\'/g, "&quot;");
    str = str.replace(/\'/g, "&#039;");
    str = str.replace(/\n/g, '<br />');
    return str;
}
/**
 * 打开表情面板
 * @param type
 */
function openFacePanel(type){
    if(type == 1){      //如果是小表情
        $('.face_chose').toggle();
        $('.face_chose_big').hide();
    }else{
        $('.face_chose').hide();
        $('.face_chose_big').toggle();
    }
}

/**
 * 上传头像
 * @param dom
 * @param username
 * @param url
 */
function updateHeadPic(dom, username, url){
    var file = new FormData();
    file.append('file', dom.files[0]);
    file.append('username', username);
    var index = layer.load(1);
    $.ajax({
        url : url,
        data : file,
        type : 'POST',
        processData : false,
        contentType : false,
        success : function(res){
            layer.close(index);
            $(dom).val('');
            var data = JSON.parse(res);
            if(data.code == 1){
                $('#user_face').attr('src', data.data.src);
            }else{
                layer.msg(data.msg);
            }
        },
        error : function(){
            layer.close(index);
            $(dom).val('');
            layer.msg('上传失败!');
        }
    });
}

/**
 * 文本域控件
 * @type {{dom: {}, init: editor.init, listener: editor.listener}}
 */
var editor = {
    dom : {},
    init : function(dom){
        this.dom = document.getElementById(dom);
        this.listener();
    },
    listener : function (){
        var self = this;
        this.dom.onkeydown = function(event){
            var code = event.keyCode || event.charCode;
            if(code == 13){
                if(event.shiftKey){     //shift + enter 换行
                    insertText(editor.dom, "\n");
                }else{
                    event.preventDefault();     //阻止默认操作
                    Im.sendMessage();       //发送消息
                }
            }
        };
    }
};

/**
 * 往光标处插入换行
 * @param obj
 * @param str
 */
function insertText(obj, str) {
    if (document.selection) {
        var sel = document.selection.createRange();
        sel.text = str;
    } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
        var startPos = obj.selectionStart,
            endPos = obj.selectionEnd,
            cursorPos = startPos,
            tmpStr = obj.value;
        obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
        cursorPos += str.length;
        obj.selectionStart = obj.selectionEnd = cursorPos;
    } else {
        obj.value += str;
    }
}

/**
 * 与某人交谈
 * @param type
 * @param name
 * @returns {boolean}
 */
function talkWith(type, name){
    if(Im.data.type != '1' || type != '1'){
        Im.session('talk_tag', name);
        Im.session('talk_type', 'friend');
        Im.buildPanel('friend', {tag:name}, 'chose');
    }
    return false;
}